/*
 * 文件名               :  SocketListener.java
 * 用途                    :  监听代理的端口
 * 最后修改日期:  $LastChangedDate: 2009-10-17 03:54:49 +0000 (Sat, 17 Oct 2009) $
 * 最后修改者     :  $LastChangedBy: wendal1985@gmail.com $
 * 创建者               :  Wendal Chen <wendal1985@gmail.com>
 */
package com.wendal.java.preproxy.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.net.ServerSocketFactory;

import com.wendal.java.preproxy.bridge.BridgeConnector;
import com.wendal.java.preproxy.thread.SocketHandler;


public class SocketListener extends Thread {

	private int port;

	private boolean flag;
	
	private BridgeConnector bridgeConnector;
	
	private SocketHandlerFinder outputFinder;
	
	public void setBridgeConnector(BridgeConnector bridgeConnector) {
		this.bridgeConnector = bridgeConnector;
	}
	
	public void setOutputFinder(SocketHandlerFinder outputFinder) {
		this.outputFinder = outputFinder;
	}
	
	public int getPort() {
		return port;
	}

	public SocketListener(int port) {
		this.port = port;
		flag = true;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

	@Override
	public void run() {
		ServerSocket serverSocket = null;
		try {
			serverSocket = ServerSocketFactory.getDefault().createServerSocket(
					port);
			Socket socket = null;
			while (flag && bridgeConnector.isAlive()) {
				socket = serverSocket.accept();
				SocketHandler socketHandler = new SocketHandler(bridgeConnector,socket);
				socketHandler.start();
				outputFinder.addObject(socketHandler);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static int f_port = 8200;
	
	public static SocketListener getSocketListener(BridgeConnector bridgeConnector,SocketHandlerFinder finder){
		f_port++;
		SocketListener listener = new SocketListener(f_port);
		listener.setBridgeConnector(bridgeConnector);
		listener.setOutputFinder(finder);
		return listener;
	}
}
